<%#
 Copyright 2013-2019 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_
const i18nToLoad = [entityInstance];
for (const idx in fields) {
    if (fields[idx].fieldIsEnum === true) {
        i18nToLoad.push(fields[idx].enumInstance);
    }
}
// const query = generateEntityQueries(relationships, entityInstance, dto);
// const queries = query.queries;
// const variables = query.variables;
// let hasManyToMany = query.hasManyToMany;
_%>
import React from 'react';
import { connect } from 'react-redux';
import { Link, RouteComponentProps } from 'react-router-dom';
import {
  Button,
  Row,
  Col,
  Label
  <% if (haveFieldWithJavadoc) { %>, UncontrolledTooltip<% } %> } from 'reactstrap';
import { AvFeedback, AvForm, AvGroup, AvInput<% if (fieldsIsReactAvField) { %>, AvField <% } %> } from 'availity-reactstrap-validation';
// tslint:disable-next-line:no-unused-variable
import {
  Translate,
  translate,
  ICrudGetAction,
  ICrudGetAllAction,
  <%_ if (fieldsContainBlob) { _%>
  setFileData,
  <% if (fieldsContainBlobOrImage) { %> openFile,<% } %>
  byteSize,
  <%_ } _%>
  ICrudPutAction
} from 'react-jhipster';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { IRootState } from 'app/shared/reducers';

<%_
let hasRelationshipQuery = false;
let otherEntityActions = new Set();
let manyToManyOwners = new Set();
let relFieldNames = new Set();
let uniqueRealtionFields = new Set();


Object.keys(differentRelationships).forEach(key => {

  const hasAnyRelationshipQuery = differentRelationships[key].some(rel =>
      (rel.relationshipType === 'one-to-one' && rel.ownerSide === true && rel.otherEntityName !== 'user')
          || rel.relationshipType !== 'one-to-many'
  );
  if (hasAnyRelationshipQuery) {
    hasRelationshipQuery = true;
    differentRelationships[key].forEach(rel => {
      if (rel.relationshipType === 'many-to-many' && rel.ownerSide === true) {
        manyToManyOwners.add(rel);
      } else {
        relFieldNames.add(rel);
      }
    });
  }
  if (differentRelationships[key].some(rel => rel.relationshipType !== 'one-to-many')) {
    const uniqueRel = differentRelationships[key][0];
    uniqueRealtionFields.add(uniqueRel.otherEntityNamePlural);
    otherEntityActions.add({
      action: `get${upperFirstCamelCase(uniqueRel.otherEntityNamePlural)}`,
      instance: `${uniqueRel.otherEntityNamePlural}`,
      entity: uniqueRel.otherEntityAngularName,
      reducer: uniqueRel.otherEntityAngularName === 'User' ? 'userManagement' : uniqueRel.otherEntityName
    });
    if (uniqueRel.otherEntityAngularName === 'User') {
_%>
import { I<%= uniqueRel.otherEntityAngularName %> } from 'app/shared/model/user.model';
<%_ if (authenticationType === 'oauth2') { _%>
import { getUsers } from 'app/shared/reducers/user-management';
<%_ } else { _%>
import { getUsers } from 'app/modules/administration/user-management/user-management.reducer';
<%_ } _%>
<%_
  } else {
    if (uniqueRel.otherEntityAngularName !== entityReactName) {
_%>
import { I<%= uniqueRel.otherEntityAngularName %> } from 'app/shared/model/<%= uniqueRel.otherEntityModelName %>.model';
  <%_ } _%>
import { getEntities as get<%= upperFirstCamelCase(uniqueRel.otherEntityNamePlural) %> } from 'app/entities/<%= uniqueRel.otherEntityPath %>/<%= uniqueRel.otherEntityFileName %>.reducer';
<%_ }
  }
}); _%>
import {
  getEntity,
  updateEntity,
  createEntity,
  <%_ if (fieldsContainBlob) { _%>
    setBlob,
  <%_ } _%>
  reset
} from './<%= entityFileName %>.reducer';
import { I<%= entityReactName %> } from 'app/shared/model/<%= entityModelFileName %>.model';
// tslint:disable-next-line:no-unused-variable
import { convertDateTimeFromServer, convertDateTimeToServer } from 'app/shared/util/date-utils';
<%_ if (relationships.filter(e => e.relationshipType === 'many-to-many') !== undefined) { _%>
import { mapIdList } from 'app/shared/util/entity-utils';
<%_ } _%>

export interface I<%= entityReactName %>UpdateProps extends StateProps, DispatchProps, RouteComponentProps<{id: string}>  {}

export interface I<%= entityReactName %>UpdateState {
  isNew: boolean;
  <%_ manyToManyOwners.forEach(val => { _%>
  ids<%= val.relationshipName %>: any[];
  <%_ }) _%>
  <%_ relFieldNames.forEach(val => { _%>
  <%= val.relationshipFieldName %>Id: string;
  <%_ }) _%>
}

export class <%= entityReactName %>Update extends React.Component<I<%= entityReactName %>UpdateProps, I<%= entityReactName %>UpdateState> {

  constructor(props) {
    super(props);
    this.state = {
      <%_ manyToManyOwners.forEach(val => { _%>
      ids<%= val.relationshipName %>: [],
      <%_ }) _%>
      <%_ relFieldNames.forEach(val => { _%>
      <%= val.relationshipFieldName %>Id: '0',
      <%_ }) _%>
      isNew: !this.props.match.params || !this.props.match.params.id,
    };
  }

  componentWillUpdate (nextProps, nextState) {
    if (nextProps.updateSuccess !== this.props.updateSuccess && nextProps.updateSuccess) {
      this.handleClose();
    }
  }

  componentDidMount() {
    <%_ if (pagination === 'infinite-scroll') { _%>
    if (!this.state.isNew) {
      this.props.getEntity(this.props.match.params.id);
    }
    <%_ } else { _%>
    if (this.state.isNew) {
      this.props.reset();
    } else {
      this.props.getEntity(this.props.match.params.id);
    }
    <%_ } _%>

    <%_ otherEntityActions.forEach(val => { _%>
    this.props.<%= val.action %>();
    <%_ }) _%>
  }

  <%_ if (fieldsContainBlob) {_%>
  onBlobChange = (isAnImage, name) => event => {
    setFileData(event, (contentType, data) => this.props.setBlob(name, data, contentType), isAnImage);
  };

  clearBlob = name => () => {
    this.props.setBlob(name, undefined, undefined);
  };
  <%_ } _%>

  saveEntity = (event, errors, values) => {
    <%_ for (idx in fields) {
        const fieldType = fields[idx].fieldType;
        const fieldName = fields[idx].fieldName;
    _%>
    <%_ if (fieldType === 'Instant' || fieldType === 'ZonedDateTime')  { _%>
    values.<%=fieldName%> = convertDateTimeToServer(values.<%= fieldName %>);
    <%_ } _%>
    <%_ } _%>

    if (errors.length === 0) {
      const { <%= entityInstance %>Entity } = this.props;
      const entity = {
        ...<%= entityInstance %>Entity,
        ...values
        <%_ manyToManyOwners.forEach(rel => { _%>
        , <%= rel.relationshipFieldNamePlural %>: mapIdList(values.<%= rel.relationshipFieldNamePlural %>)
        <%_ }) _%>
      }

      if (this.state.isNew) {
        this.props.createEntity(entity);
      } else {
        this.props.updateEntity(entity);
      }
    }
  }

  handleClose = () => {
    this.props.history.push('/entity/<%= entityFileName %>');
  }

  render() {
    const { <%= entityInstance %>Entity,<%
    uniqueRealtionFields.forEach(rel => {
    %> <%= rel %>,<% }) %> loading, updating } = this.props;
    const { isNew } = this.state;

    <%_ for (var i = 0; i < blobFields.length; i++) { _%>
    <%_
      const b = blobFields[i];
      if (i === 0) {
    _%>
      const {
      <%_ } _%>
      <%= b.fieldName %>
      <%_ if (b.fieldTypeBlobContent !== 'text') { _%>
      , <%= b.fieldName %>ContentType
      <%_ } _%>
      <%_ if (i+1 === blobFields.length) { _%>
      } = <%= entityInstance %>Entity;
      <%_ } else { _%>
      ,
      <%_ } _%>
    <%_ } _%>

    return (
      <div>
      <Row className="justify-content-center">
        <Col md="8">
          <h2 id="<%= i18nKeyPrefix %>.home.createOrEditLabel">
            <Translate contentKey="<%= i18nKeyPrefix %>.home.createOrEditLabel">Create or edit a <%= entityClass %></Translate>
          </h2>
        </Col>
      </Row>
      <Row className="justify-content-center">
        <Col md="8">
          { loading ? <p>Loading...</p> :
          <AvForm model={isNew ? {} : <%= entityInstance %>Entity} onSubmit={this.saveEntity} >
            { !isNew ?
              <AvGroup>
                <Label for="id"><Translate contentKey="global.field.id">ID</Translate></Label>
                <AvInput id="<%= entityFileName %>-id" type="text" className="form-control" name="id" required readOnly/>
              </AvGroup>
              : null
            }
            <%_ for (idx in fields) {
                const fieldType = fields[idx].fieldType;
                const fieldName = fields[idx].fieldName;
                const fieldNameHumanized = fields[idx].fieldNameHumanized;
            _%>
            <AvGroup>
            <%_ if (fieldType === 'Boolean') { _%>
              <Label id="<%= fieldName %>Label" check>
                <AvInput id="<%= entityFileName %>-<%= fieldName %>" type="checkbox" className="form-control" name="<%= fieldName %>" />
                <Translate contentKey="<%= i18nKeyPrefix %>.<%= fieldName %>">
                  <%= fieldNameHumanized %>
                </Translate>
              </Label>
            <%_ } else if (['Instant', 'ZonedDateTime'].includes(fieldType)) { _%>
              <Label id="<%= fieldName %>Label" for="<%= fieldName %>">
                <Translate contentKey="<%= i18nKeyPrefix %>.<%= fieldName %>">
                  <%= fieldNameHumanized %>
                </Translate>
              </Label>
              <AvInput
                id="<%= entityFileName %>-<%= fieldName %>"
                type="datetime-local"
                className="form-control"
                name="<%= fieldName %>"
                placeholder={"YYYY-MM-DD HH:mm"}
                value={isNew ? null : convertDateTimeFromServer(this.props.<%= entityInstance %>Entity.<%= fieldName %>)}
                <%- include react_validators %>
              />
            <%_ } else if (fieldType === 'LocalDate') { _%>
              <Label id="<%= fieldName %>Label" for="<%= fieldName %>">
                <Translate contentKey="<%= i18nKeyPrefix %>.<%= fieldName %>">
                  <%= fieldNameHumanized %>
                </Translate>
              </Label>
              <AvField
                id="<%= entityFileName %>-<%= fieldName %>"
                type="date"
                className="form-control"
                name="<%= fieldName %>"
                <%- include react_validators %>
              />
            <%_
              } else if (fields[idx].fieldIsEnum) {
                const values = fields[idx].fieldValues.replace(/\s/g, '').split(',');
            _%>
              <Label id="<%= fieldName %>Label">
                <Translate contentKey="<%= i18nKeyPrefix %>.<%= fieldName %>">
                  <%= fieldNameHumanized %>
                </Translate>
              </Label>
              <AvInput
                id="<%= entityFileName %>-<%= fieldName %>"
                type="select"
                className="form-control"
                name="<%= fieldName %>"
                value={(!isNew && <%= entityInstance %>Entity.<%= fieldName%>) || '<%= values[0] %>'}
              >
              <%_
                const enumPrefix = angularAppName + '.'+ fieldType;
                for (key in values) {
                    const value = values[key];
              _%>
                <option value="<%= value %>">
                <%_ if (enableTranslation) { _%>
                  <Translate contentKey="<%= enumPrefix %>.<%= value %>" />
                <%_ } else { _%>
                  <%= value %>
                <%_ } _%>
                </option>
              <%_ } _%>
              </AvInput>
            <%_ } else if (['Integer', 'Long', 'Float', 'Double'].includes(fieldType)) { _%>
              <Label id="<%= fieldName %>Label" for="<%= fieldName %>">
                <Translate contentKey="<%= i18nKeyPrefix %>.<%= fieldName %>">
                  <%= fieldNameHumanized %>
                </Translate>
              </Label>
              <AvField id="<%= entityFileName %>-<%= fieldName %>" type="string" className="form-control" name="<%= fieldName %>" <%- include react_validators %> />
            <%_
            } else if (['byte[]', 'ByteBuffer'].includes(fieldType)) {

              const fieldBlobType = fields[idx].fieldTypeBlobContent;
              if (fieldBlobType !== 'text') {
                const isAnImage = fieldBlobType === 'image';
                const capitalizedFirstLetter =  _.upperFirst(fieldName);

            _%>

            <AvGroup>
              <Label id="<%= fieldName %>Label" for="<%= fieldName %>">
                <Translate contentKey="<%= i18nKeyPrefix %>.<%= fieldName %>">
                  <%= fieldNameHumanized %>
                </Translate>
              </Label>
              <br />
              {<%= fieldName %> ? (
                <div>
                  <a onClick={openFile(<%= fieldName %>ContentType, <%= fieldName %>)}>
                  <%_ if (isAnImage) { _%>
                    <img src={`data:${<%= fieldName %>ContentType};base64,${<%= fieldName %>}`} style={{ maxHeight: '100px' }} />
                  <%_ } else { _%>
                    <Translate contentKey="entity.action.open">Open</Translate>
                  <%_ } _%>
                  </a>
                  <br />
                  <Row>
                    <Col md="11">
                      <span>{<%= fieldName %>ContentType}, {byteSize(<%= fieldName %>)}</span>
                    </Col>
                    <Col md="1">
                      <Button color="danger" onClick={this.clearBlob('<%= fieldName %>')}><FontAwesomeIcon icon="times-circle" /></Button>
                    </Col>
                  </Row>
                </div>
              ) : null}
              <input id="file_<%= fieldName %>" type="file" onChange={this.onBlobChange(<%= isAnImage %>, '<%= fieldName %>')} <% if (isAnImage) { %>accept="image/*"<% } %> />
              <AvInput type="hidden" name="<%= fieldName %>" value={<%= fieldName %>} <%- include react_validators %>/>
            </AvGroup>

            <%_ } else { _%>
              <Label id="<%= fieldName %>Label" for="<%= fieldName %>">
                <Translate contentKey="<%= i18nKeyPrefix %>.<%= fieldName %>">
                  <%= fieldNameHumanized %>
                </Translate>
              </Label>
              <AvInput id="<%= entityFileName %>-<%= fieldName %>" type="textarea" name="<%= fieldName %>" <%- include react_validators %>/>
              <%_ } _%>
            <%_ } else { _%>
            <Label id="<%= fieldName %>Label" for="<%= fieldName %>">
              <Translate contentKey="<%= i18nKeyPrefix %>.<%= fieldName %>">
                <%= fieldNameHumanized %>
              </Translate>
            </Label>
            <AvField id="<%= entityFileName %>-<%= fieldName %>" type="text" name="<%= fieldName %>" <%- include react_validators %>/>
          <%_ } _%>
            <%_ if (fields[idx].javadoc) { _%>
            <UncontrolledTooltip target="<%= fieldName %>Label">
              <%_ if (enableTranslation) { _%>
              <Translate contentKey="<%= i18nKeyPrefix %>.help.<%= fieldName %>"/>
              <%_ } else { _%>
              <%= fields[idx].javadoc %>
              <%_ } _%>
            </UncontrolledTooltip>
            <%_ } _%>
            </AvGroup>
            <%_ } _%>
            <%_ relationships.forEach(rel => {
                const relationshipType = rel.relationshipType;
                const ownerSide = rel.ownerSide;
                const otherEntityName = rel.otherEntityName;
                const otherEntityNamePlural = rel.otherEntityNamePlural;
                const otherEntityNameCapitalized = rel.otherEntityNameCapitalized;
                const relationshipName = rel.relationshipName;
                const relationshipNameHumanized = rel.relationshipNameHumanized;
                const relationshipFieldName = rel.relationshipFieldName;
                const relationshipFieldNamePlural = rel.relationshipFieldNamePlural;
                const otherEntityField = rel.otherEntityField;
                const otherEntityFieldCapitalized = rel.otherEntityFieldCapitalized;
                const relationshipRequired = rel.relationshipRequired;
                const translationKey = `${i18nKeyPrefix}.${relationshipName}`; _%>
                <%_ if (relationshipType === 'many-to-one' || (relationshipType === 'one-to-one' && ownerSide === true && otherEntityName === 'user')) { _%>
            <AvGroup>
              <Label for="<%= relationshipFieldName %>.<%= otherEntityField %>">
                <Translate contentKey="<%= translationKey %>"><%= relationshipNameHumanized %></Translate>
              </Label>
              <%_ if (dto === 'no') { _%>
                  <%_ if (!relationshipRequired) { _%>
              <AvInput
                id="<%= entityFileName %>-<%= relationshipName %>"
                type="select"
                className="form-control"
                name="<%= relationshipFieldName %>.id"
              >
                <option value="" key="0" />
                {
                  <%= otherEntityNamePlural %> ? <%= otherEntityNamePlural %>.map(otherEntity =>
                    <option
                      value={otherEntity.id}
                      key={otherEntity.id}>
                      {otherEntity.<%=otherEntityField%>}
                    </option>
                  ) : null
                }
              </AvInput>
                <%_ } else { _%>
              <AvInput
                id="<%= entityFileName %>-<%= relationshipName %>"
                type="select"
                className="form-control"
                name="<%= relationshipFieldName %>.id"
                value={isNew ? <%= otherEntityNamePlural %>[0] && <%= otherEntityNamePlural %>[0].id : <%= entityInstance %>Entity.<%= relationshipName %>.id}
                required
              >
                {
                  <%= otherEntityNamePlural %> ? <%= otherEntityNamePlural %>.map(otherEntity =>
                    <option
                      value={otherEntity.id}
                      key={otherEntity.id}>
                      {otherEntity.<%=otherEntityField%>}
                    </option>
                  ) : null
                }
              </AvInput>
              <AvFeedback><Translate contentKey="entity.validation.required">This field is required.</Translate></AvFeedback>
              <%_ } _%>
              <%_ } else { _%>
                <%_ if (!relationshipRequired) { _%>
                  <AvInput
                    id="<%= entityFileName %>-<%= relationshipName %>"
                    type="select"
                    className="form-control"
                    name="<%= relationshipFieldName %>Id"
                  >
                    <option value="" key="0" />
                    {
                      <%= otherEntityNamePlural %> ? <%= otherEntityNamePlural %>.map(otherEntity =>
                        <option
                          value={otherEntity.id}
                          key={otherEntity.id}>
                          {otherEntity.<%=otherEntityField%>}
                        </option>
                      ) : null
                    }
                  </AvInput>
                <%_ } else { _%>
                  <AvInput
                    id="<%= entityFileName %>-<%= relationshipName %>"
                    type="select"
                    className="form-control"
                    name="<%= relationshipFieldName %>Id"
                    required
                  >
                    {
                      <%= otherEntityNamePlural %> ? <%= otherEntityNamePlural %>.map(otherEntity =>
                        <option
                          value={otherEntity.id}
                          key={otherEntity.id}>
                          {otherEntity.<%=otherEntityField%>}
                        </option>
                      ) : null
                    }
                  </AvInput>
                  <AvFeedback><Translate contentKey="entity.validation.required">This field is required.</Translate></AvFeedback>
                <%_ } _%>
              <%_ } _%>
            </AvGroup>
                <%_ } else if (relationshipType === 'one-to-one' && ownerSide === true) { _%>
            <AvGroup>
              <Label for="<%= relationshipFieldName %>.<%= otherEntityField %>">
                <Translate contentKey="<%= translationKey %>"><%= relationshipNameHumanized %></Translate>
              </Label>
                <%_ if (dto === 'no') { _%>
                  <AvInput
                    id="<%= entityFileName %>-<%= relationshipName %>"
                    type="select"
                    className="form-control"
                    name="<%= relationshipFieldName %>.id"
                  >
                    <option value="" key="0" />
                    {
                      <%= otherEntityNamePlural %> ? <%= otherEntityNamePlural %>.map(otherEntity =>
                        <option
                          value={otherEntity.id}
                          key={otherEntity.id}>
                          {otherEntity.<%=otherEntityField%>}
                        </option>
                      ) : null
                    }
                  </AvInput>
                <%_ } else { _%>
                  <AvInput
                    id="<%= entityFileName %>-<%= relationshipName %>"
                    type="select"
                    className="form-control"
                    name="<%= relationshipFieldName %>Id"
                  >
                    <option value="" key="0" />
                    {
                      <%= otherEntityNamePlural %> ? <%= otherEntityNamePlural %>.map(otherEntity =>
                        <option
                          value={otherEntity.id}
                          key={otherEntity.id}>
                          {otherEntity.<%=otherEntityField%>}
                        </option>
                      ) : null
                    }
                  </AvInput>
                <%_ } _%>
            </AvGroup>
                <%_ } else if (relationshipType === 'many-to-many' && rel.ownerSide === true) { _%>
            <AvGroup>
              <Label for="<%= otherEntityNamePlural %>"><Translate contentKey="<%= translationKey %>"><%= relationshipNameHumanized %></Translate></Label>
              <AvInput
                id="<%= entityFileName %>-<%= relationshipName %>"
                type="select"
                multiple
                className="form-control"
                name="<%= relationshipFieldNamePlural %>"
                value={<%= entityInstance %>Entity.<%= relationshipFieldNamePlural %> && <%= entityInstance %>Entity.<%= relationshipFieldNamePlural %>.map(e => e.id)}
              >
                <option value="" key="0" />
                {
                  (<%= otherEntityNamePlural %>) ? <%= otherEntityNamePlural %>.map(otherEntity =>
                  <option
                      value={otherEntity.id}
                      key={otherEntity.id}>
                      {otherEntity.<%=otherEntityField%>}
                  </option>
                  ) : null
                }
              </AvInput>
            </AvGroup>
            <%_ } _%>
          <%_ }) _%>
            <Button tag={Link} id="cancel-save" to="/entity/<%= entityFileName %>" replace color="info">
              <FontAwesomeIcon icon="arrow-left" />&nbsp;
              <span className="d-none d-md-inline" ><Translate contentKey="entity.action.back">Back</Translate></span>
            </Button>
            &nbsp;
            <Button color="primary" id="save-entity" type="submit" disabled={updating}>
              <FontAwesomeIcon icon="save" />&nbsp;
              <Translate contentKey="entity.action.save">Save</Translate>
            </Button>
          </AvForm>
          }
        </Col>
      </Row>
    </div>
    );
  }
}

const mapStateToProps = (storeState: IRootState) => ({
  <%_ otherEntityActions.forEach(val => { _%>
    <%= val.instance %>: storeState.<%= val.reducer %>.<%= val.entity === 'User' ? val.instance : 'entities' %>,
  <%_ }) _%>
  <%= entityInstance %>Entity: storeState.<%= entityInstance %>.entity,
  loading: storeState.<%= entityInstance %>.loading,
  updating: storeState.<%= entityInstance %>.updating,
  updateSuccess: storeState.<%= entityInstance %>.updateSuccess,
});

const mapDispatchToProps = {
  <%_ otherEntityActions.forEach(val => { _%>
  <%= val.action %>,
  <%_ }) _%>
  getEntity,
  updateEntity,
  <%_ if (fieldsContainBlob) { _%>
  setBlob,
  <%_ } _%>
  createEntity,
  reset
};

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;

export default connect(mapStateToProps, mapDispatchToProps)(<%= entityReactName %>Update);
